<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="modeFormRef" :rules="rules" :model="ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="型号名称" prop="name">
							<el-input v-model="ruleForm.name" placeholder="请输入型号名称" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue';
import { useEquipmentmode, Equipmentmode } from './equipmentmode';
import { ElMessage } from 'element-plus';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const modeFormRef = ref();
const ruleForm = reactive<Equipmentmode>({
	name: '', // 型号名称
});
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
const rules = ref({
	name: [
		{ required: true, type: 'string', message: '型号不能为空', trigger: 'blur' },
		{ pattern: /[\u4e00-\u9fa5A-Za-z0-9]/, min: 2, max: 20, message: '请输入2-20个中英文字符名称', trigger: 'blur' },
	],
});

// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
	if (type === 'edit') {
		console.log(row);
		// ruleForm.value = row;
		state.dialog.title = '修改信息';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '新增型号';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		nextTick(() => {
			modeFormRef.value.resetFields();
		});
	}
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	if (!modeFormRef.value) return;
	modeFormRef.value.validate((valid: any) => {
		if (valid) {
			useEquipmentmode()
				.addEquipmentmode(ruleForm)
				.then(() => {
					closeDialog();
					emit('refresh');
				})
				.then(() => {
					ElMessage.success('添加成功！');
				})
				.catch(() => {
					ElMessage.error('添加失败');
				});
		}
	});
	// closeDialog();
	// emit('refresh');
	// if (state.dialog.type === 'add') { }
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
